import KeySymbol from "./keySymbol"

/**
 * 处理父节点是否可以展开
 *  
 * @param {*} row 
 * @param {*} data 
 */
function parentExpandableHandler(row, data) {

  let siblings = data.filter(item => {
    return item[KeySymbol.parentIdSymbol] === row[KeySymbol.parentIdSymbol];
  });
  if (siblings.length <= 1) {
    let parent = data.find(item => {
      return item[KeySymbol.rowIdSymbol] === row[KeySymbol.parentIdSymbol];
    });

    if (parent) {
      parent[KeySymbol.hasChildrenSymbol] = false;
    }
  }
}

/**
 * 移除后代节点
 * 
 * @param {*} row
 * @param {*} data  
 */
function removeChildren(row, data) {
  if (row) {
    if (row[KeySymbol.hasChildrenSymbol]) {
      let children = data.filter(item => {
        return item[KeySymbol.parentIdSymbol] === row[KeySymbol.rowIdSymbol];
      });
      children.forEach(item => {
        const index = data.indexOf(item);
        data.splice(index, 1);
        if (item[KeySymbol.hasChildrenSymbol]) {
          removeChildren(item, data);
        }
      });
    }
  }
}

/**
 * 移除当前行
 * 
 * @param {*} row
 * @param {*} data  
 */
function removeCurrent(row, data) {
  const index = data.indexOf(row);
  if (index > -1) {
    data.splice(index, 1);
  }
}


export default (rowKey, data, {
  treeKey
}) => {

  let row = data.find(item => {
    return item[treeKey] === rowKey;
  });
  if (row) {
    parentExpandableHandler(row, data);
    removeChildren(row, data);
    removeCurrent(row, data);
  }
}
